
//% color="#CD853F" iconWidth=50 iconHeight=40
namespace DTC{

    //% block="加载数据" blockType="tag"
    export function initmodel() {}
    //% block="初始化模块" blockType="command"
    export function init(parameter: any, block: any) {

        Generator.addImport(`from ImageClassifier import ImageClassifier
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
from sklearn.preprocessing import LabelEncoder
import numpy as np
import cv2
import joblib`)
        Generator.addCode(`images_class = ImageClassifier()\n`)

    }
    //% block="创建VideoCapture对象[VD],打开摄像头直到成功 编号[CAMNUM]" blockType="command"
    //% VD.shadow="normal" VD.defl="vd"
    //% CAMNUM.shadow="number" CAMNUM.defl="0"
    export function readcap(parameter: any, block: any) {
        let num=parameter.CAMNUM.code;
        let vd=parameter.VD.code;

        Generator.addCode(`${vd} = cv2.VideoCapture(${num})`)
            
        Generator.addCode(`while not vd.isOpened():
    continue`)    
    }
    //% block="从VideoCapture对象[VD]中抓取下一帧[IMG]以及状态[RET]" blockType="command"
    //% VD.shadow="normal" VD.defl="vd"
    //% IMG.shadow="normal" IMG.defl="img"
    //% RET.shadow="normal" RET.defl="ret"
    export function readimg(parameter: any, block: any) {
        let vd=parameter.VD.code;
        let img=parameter.IMG.code;
        let ret=parameter.RET.code;
        Generator.addCode(`${ret}, ${img} = ${vd}.read()`)
        
    }
    //% block="创建窗口[TEXT]并设置为全屏" blockType="command"
    //% TEXT.shadow="string" TEXT.defl="cvwindow"
    export function cv_collect_set_winname(parameter: any, block: any) {
        let text=parameter.TEXT.code;
        Generator.addCode(`cv2.namedWindow(${text},cv2.WND_PROP_FULLSCREEN)`)
        Generator.addCode(`cv2.setWindowProperty(${text}, cv2.WND_PROP_FULLSCREEN, cv2.WINDOW_FULLSCREEN)`)
    }
    //% block="调整图像[IMG]尺寸为宽[W]高[H]输出[OUT]" blockType="command"
    //% IMG.shadow="normal" IMG.defl="img"
    //% W.shadow="number" W.defl="640"
    //% H.shadow="number" H.defl="480"
    //% OUT.shadow="normal" OUT.defl="outlmg"
    export function cv_collect_resize(parameter: any, block: any) {
        let img=parameter.IMG.code;
        let w=parameter.W.code;
        let h=parameter.H.code;
        let out=parameter.OUT.code;
        Generator.addCode(`${out} = cv2.resize(${img}, (${w}, ${h}))`)
    }
    //% block="在摄像头[IMG]画面上显示文字[TEXT]大小[SIZE] 颜色R[R]G[G]B[B] 坐标X[X]Y[Y]将图像存入[OUT]中" blockType="command"
    //% IMG.shadow="normal" IMG.defl="img"
    //% TEXT.shadow="string" TEXT.defl="你好"
    //% SIZE.shadow="number"   SIZE.defl="25"
    //% R.shadow="range"   R.params.min=0    R.params.max=255    R.defl=50
    //% G.shadow="range"   G.params.min=0    G.params.max=255    G.defl=200
    //% B.shadow="range"   B.params.min=0    B.params.max=255    B.defl=0
    //% X.shadow="number"   X.defl="10"
    //% Y.shadow="number"   Y.defl="20"
    //% OUT.shadow="normal" OUT.defl="outlmg"
    export function drawText(parameter: any, block: any) {
        let img=parameter.IMG.code;
        let txt=parameter.TEXT.code;
        let size=parameter.SIZE.code;
        let r=parameter.R.code;
        let g=parameter.G.code;
        let b=parameter.B.code;
        let x=parameter.X.code;
        let y=parameter.Y.code;
        let out=parameter.OUT.code;
         Generator.addImport(`import matplotlib.font_manager\nimport sys\nimport os`)
         Generator.addDeclaration("drawCountplot",`if "linux" in sys.platform:
    font_path = 'HYQiHei_50S.ttf'
else: 
    font_path = matplotlib.font_manager.findfont('SimHei')

if not os.path.isfile(font_path):
    font_path = None`)
        // cv2.putText(frame, f"Freshness: {freshness}", (10, 30),cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
        // Generator.addCode(`cv2.putText(${img},${txt},(${x},${y}), cv2.FONT_HERSHEY_SIMPLEX, ${size}, (${r},${g},${b}),2)`)
        Generator.addCode(`${out}  = images_class.drawChinese(text=str(${txt}),x=${x}, y=${y},size=${size},r= ${r},g=${g},b=0,a=${b},img=${img},font=font_path)`)    
    }
    //% block="在窗口[TEXT]显示图像[IMG]" blockType="command"
    //% TEXT.shadow="string" TEXT.defl="cvwindow"
    //% IMG.shadow="normal" IMG.defl="img"
    export function cv_collect_show(parameter: any, block: any) {
        let text=parameter.TEXT.code;
        let img=parameter.IMG.code;
        Generator.addCode(`cv2.imshow(${text}, ${img})`)
    }
  
    //% block="每[TI]毫秒刷新图像" blockType="command"
    
    //% TI.shadow="number" TI.defl="1"
    export function cv_collect_waitKey(parameter: any, block: any) {
  
        let ti=parameter.TI.code;
        Generator.addCode(`key = cv2.waitKey(${ti})`)
    }


    //% block="加载图片数据集路径[DIR]，将图像数据存入在变量[IMG]和图像标签存入在变量[LAB]" blockType="command"
    //% DIR.shadow="string" DIR.defl="dataset"
    //% IMG.shadow="normal" IMG.defl="img"
    //% LAB.shadow="normal" LAB.defl="lab"
    export function readFile(parameter: any, block: any) {
        let DIR=parameter.DIR.code; 
        let IMG=parameter.IMG.code;
        let LAB=parameter.LAB.code;

        Generator.addCode(`${IMG}, ${LAB} = images_class.load_images_from_folder(r${DIR})\n`)
        

    }
    //% block="处理数据" blockType="tag"
    export function initmodel1() {}
    //% block="在图像数据[IMG]上提取HOG特征，将特征数据存入变量[HOG]" blockType="command"
    //% IMG.shadow="normal" IMG.defl="img"
    //% HOG.shadow="normal" HOG.defl="hog_features"
    export function getHOG(parameter: any, block: any) {
        let IMG=parameter.IMG.code; 
        let HOG=parameter.HOG.code;
        Generator.addCode(`${HOG} = images_class.extract_hog_features(${IMG})`)

    }

    //% block="在图像数据[IMG]上提取RGB直方图特征，将特征数据存入变量[COLOR1]" blockType="command"
    //% IMG.shadow="normal" IMG.defl="img"
    //% COLOR1.shadow="normal" COLOR1.defl="color_features"
    export function getcolor(parameter: any, block: any) {
        let IMG=parameter.IMG.code; 
        let COLOR1=parameter.COLOR1.code;
        Generator.addCode(`${COLOR1} = images_class.extract_color_features(${IMG})`)

    }
        //% block="合并[HOG]HOG特征和[COLOR1]RGB直方图特征，返回特征数据存入变量[X]" blockType="command"
    //% HOG.shadow="normal" HOG.defl="hog_features"
    //% COLOR1.shadow="normal" COLOR1.defl="color_features"
    //% X.shadow="normal" X.defl="X"
    export function getallfeat1(parameter: any, block: any) {
        let HOG=parameter.HOG.code; 
        let COLOR1=parameter.COLOR1.code;
        let X=parameter.X.code;
        Generator.addCode(`${X} = np.hstack((${HOG}, ${COLOR1}))`)
    }
    //% block="使用特征集[X]数据" blockType="command"
    //% X.shadow="normal" X.defl="X"
 
    export function getallfeat(parameter: any, block: any) {
        let X=parameter.X.code;
        Generator.addCode(`
label_encoder = LabelEncoder()
y_va = label_encoder.fit_transform(lab)
X_train, X_test, y_train, y_test = train_test_split(${X},y_va, test_size=0.3, random_state=42)
`)
    }

//     //% block="在图像数据[IMG]上提取HOG特征和RGB直方图特征，将数据存入变量[FEA]中" blockType="command"
//     //% IMG.shadow="normal" IMG.defl="img"
//     //% FEA.shadow="normal" FEA.defl="features"
//     export function getallfeat11(parameter: any, block: any) {
//         let IMG=parameter.IMG.code; 
//         let FEA=parameter.FEA.code;
//         Generator.addCode(`hog_features = images_class.extract_hog_features(${IMG})
// color_features = images_class.extract_color_features(${IMG})
// ${FEA} = np.hstack((hog_features, color_features))
// `)
//     }
    // //% block="---" blockType="tag"
    // export function initmodel2() {}
    // //% block="创建特征编码器[OBJECT]" blockType="command"
    // //% OBJECT.shadow="normal" OBJECT.defl="label_encoder"
    // export function Sklearn_initOBJ(parameter: any, block: any) {
    //     let obj=parameter.OBJECT.code;  
    //     Generator.addCode(`${obj} = LabelEncoder()`)  
    // }

    // //% block="对象名[OBJECT]经编码器拟合并标准化[STR]的数据结果返回变量[VALUE]中" blockType="command"
    // //% OBJECT.shadow="normal" OBJECT.defl="label_encoder"
    // //% STR.shadow="normal" STR.defl="lab"
    // //% VALUE.shadow="normal" VALUE.defl="y"
    // export function Sklearn_initread(parameter: any, block: any) {
    //     let obj=parameter.OBJECT.code;  
    //     let str=parameter.STR.code;  
    //     let value=parameter.VALUE.code; 
    //     Generator.addCode(`${value} = ${obj}.fit_transform(${str})\n`) 
    // }
    

    // //% block="随机划分特征集[X]标签集[Y]样本占比[SIZE]返回划分的训练特征集[XTRAIN]测试特征集[Xtest]训练标签集[YTRAIN]测试标签集[Ytest]" blockType="command"
    // //% SIZE.shadow="range" SIZE.params.min=0    SIZE.params.max=1    SIZE.defl=0.3
    // //% X.shadow="normal" X.defl="X"
    // //% Y.shadow="normal" Y.defl="y"
    // //% XTRAIN.shadow="normal" XTRAIN.defl="X_train"
    // //% Xtest.shadow="normal" Xtest.defl="X_test"
    // //% YTRAIN.shadow="normal" YTRAIN.defl="y_train"
    // //% Ytest.shadow="normal" Ytest.defl="y_test"
    // export function train_test_split(parameter: any, block: any) {
    //     let x=parameter.X.code;
    //     let y=parameter.Y.code;
    //     let size=parameter.SIZE.code;
 
    //     let xtrain=parameter.XTRAIN.code;
    //     let ytrain=parameter.YTRAIN.code;
    //     let xtest=parameter.Xtest.code;
    //     let ytest=parameter.Ytest.code;
    //     Generator.addCode(`${xtrain}, ${xtest}, ${ytrain}, ${ytest} = train_test_split(${x},${y}, test_size=${size}, random_state=42)\n`)

    // }
    //% block="---" blockType="tag"
    export function initmodel3() {}
    //% block="构建决策树模型[CLF]" blockType="command"
    //% CLF.shadow="normal" CLF.defl="clf_tree"
    export function Sklearn_initOBJ1(parameter: any, block: any) {
        let obj=parameter.CLF.code;

        Generator.addCode(`${obj} = DecisionTreeClassifier(random_state=42)\n`)  
    }
    //% block="对象名[CLF]设置修剪参数分割标准[A]系数最大深度[B]最小分裂样本数[C]最小叶节点样本数[D]最大叶节点数量[E]" blockType="command"
    //% CLF.shadow="normal" CLF.defl="clf_tree"
    //% A.shadow="dropdown" A.options=A
    //% B.shadow="number" B.defl=3
    //% C.shadow="number" C.defl=5
    //% D.shadow="number" D.defl=2
    //% E.shadow="number" E.defl=10
    export function setparameter(parameter: any, block: any) {
        let CLF=parameter.CLF.code;
        let a=parameter.A.code;
        let b=parameter.B.code;
        let c=parameter.C.code;
        let d=parameter.D.code;
        let e=parameter.E.code;
        Generator.addCode(`${CLF}.set_params(criterion='${a}', max_depth=${b}, min_samples_split=${c}, min_samples_leaf=${d}, max_leaf_nodes=${e})`)
        }
    //% block="查找最佳参数，在决策树模型[CLF]中使用" blockType="command"
    //% CLF.shadow="normal" CLF.defl="clf_tree"
    export function setparameter1(parameter: any, block: any) {
        let CLF=parameter.CLF.code;
        Generator.addCode(`
param_grid = {
    'criterion': ['entropy', 'gini'],  
    'max_depth': [3, 5, 7, 10, None],  
    'min_samples_split': [2, 5, 10],  
    'min_samples_leaf': [1, 2, 5],     
    'max_leaf_nodes': [10, 20, None]   
}

grid_search = GridSearchCV(${CLF}, param_grid, cv=5)
grid_search.fit(X_train, y_train)
${CLF} = grid_search.best_estimator_`)
    }
    // //% block="使用网络搜索在训练特征集[XTRAIN]和训练标签集[YTRAIN]上获取最佳参数" blockType="command"
    // //% XTRAIN.shadow="normal" XTRAIN.defl="X_train"
    // //% YTRAIN.shadow="normal" YTRAIN.defl="y_train"
    // export function train(parameter: any, block: any) {
    //     let xtrain=parameter.XTRAIN.code;
    //     let ytrain=parameter.YTRAIN.code;
    //     Generator.addCode(`grid_search.fit(${xtrain}, ${ytrain})`)
    // }
    
    //% block="获取[DATA]的最佳参数" blockType="reporter"
    //% DATA.shadow="dropdown" DATA.options="DATA"
    export function getbest(parameter: any, block: any) {
        let DATA=parameter.DATA.code;
        if(`${DATA}` ==="all")
            Generator.addCode(`grid_search.best_params_`)
        else{
            Generator.addCode(`grid_search.best_params_["${DATA}"]`)
        }
    }
    // //% block="对象名[CLF]使用最佳参数" blockType="command"
    // //% CLF.shadow="normal" CLF.defl="clf_tree"
    // export function getbest1(parameter: any, block: any) {
    //     let CLF=parameter.CLF.code;
    //     Generator.addCode(`${CLF} = grid_search.best_estimator_ `)
    // }


    //% block="开始训练[OBJECT]模型" blockType="command"
    //% OBJECT.shadow="normal" OBJECT.defl="clf_tree"
    export function Sklearn_initread2(parameter: any, block: any) {
        let obj=parameter.OBJECT.code;  
        Generator.addCode(`${obj}.fit(X_train,y_train)`) 
    }    
    //% block="模型操作" blockType="tag"
    export function initmodel4() {}
    // //% block="对象名[OBJECT]对[DATA]进行预测并返回结果" blockType="reporter"
    // //% OBJECT.shadow="normal" OBJECT.defl="clf_tree"
    // //% DATA.shadow="normal" DATA.defl="X_test"
    // export function predict(parameter: any, block: any) {
    //     let obj=parameter.OBJECT.code;  
    //     let data=parameter.DATA.code;  
    //     Generator.addCode(``) 
    // }
    //% block="计算决策树模型[OBJECT]准确率" blockType="reporter"
    //% OBJECT.shadow="normal" OBJECT.defl="clf_tree"

    export function predict_and_evaluate(parameter: any, block: any) {
        let obj=parameter.OBJECT.code;
        Generator.addCode(`round(accuracy_score(y_test, ${obj}.predict(X_test)),2)`);  // 计算准确度
    }
    // //% block="用预测数据[y_pred]和测试标签集[TRUE_LABELS]及标签编码器[ENCODER]生成分类报告" blockType="reporter"
    // //% y_pred.shadow="normal" y_pred.defl="y_pred" 
    // //% TRUE_LABELS.shadow="normal" TRUE_LABELS.defl="y_test"
    // //% ENCODER.shadow="normal" ENCODER.defl="label_encoder"
    // export function generate_classification_report(parameter: any, block: any) {
    //     let y_pred = parameter.y_pred.code;  // 真实标签
    //     let true_labels = parameter.TRUE_LABELS.code;  // 真实标签
    //     let encoder = parameter.ENCODER.code;  // 标签编码器

    //     Generator.addCode(`classification_report(${true_labels}, ${y_pred}, target_names=${encoder}.classes_)`);  // 生成分类报告
    // }
    // //% block="用预测数据[y_pred]和测试标签集[TRUE_LABELS]生成混淆矩阵" blockType="reporter"
    // //% y_pred.shadow="normal" y_pred.defl="y_pred" 
    // //% TRUE_LABELS.shadow="normal" TRUE_LABELS.defl="y_test"
    // export function generate_confusion_matrix(parameter: any, block: any) {
    //     let y_pred = parameter.y_pred.code;  // 真实标签
    //     let true_labels = parameter.TRUE_LABELS.code;  // 真实标签
    //     Generator.addCode(`confusion_matrix(${true_labels}, ${y_pred})`);  // 生成混淆矩阵
    // }

    //% block="特征编码器[OBJECT]和决策树模型[LAB]预测特征[FEA]结果转换回原始的类别标签" blockType="command"
    //% OBJECT.shadow="normal" OBJECT.defl="label_encoder"
    //% LAB.shadow="normal" LAB.defl="clf_tree"
    //% FEA.shadow="normal" FEA.defl="features"
    export function Sklearn_initread1(parameter: any, block: any) {
        let obj=parameter.OBJECT.code;  
        let lab=parameter.LAB.code;  
        let fea=parameter.FEA.code;
        Generator.addCode(`prediction_va = ${lab}.predict([${fea}])
class_label = ${obj}.inverse_transform(prediction_va)[0]`) 
    }
    
    //% block="标签类别" blockType="reporter"
    export function getlabel(parameter: any, block: any) {
        Generator.addCode(`class_label`)
    }
    //% block="决策树模型[LAB]预测特征[FEA]结果返回置信度" blockType="command"
   //% LAB.shadow="normal" LAB.defl="clf_tree"
    //% FEA.shadow="normal" FEA.defl="features"
    export function Sklearn_initreadi(parameter: any, block: any) {
        let lab=parameter.LAB.code;  
        let fea=parameter.FEA.code;
        Generator.addCode(`
predict_proba = ${lab}.predict_proba([${fea}])[0]      
class_confidence = predict_proba[${lab}.predict([${fea}])]`) 
    }
    //% block="置信度" blockType="reporter"
    export function predict_proba(parameter: any, block: any) {
        Generator.addCode(`(round(class_confidence[0],2))`)
    }
    //% block="---" blockType="tag"    export function initmodel5() {}
    //% block="对象名[CLF]保存模型到[PATH]" blockType="command"
    //% CLF.shadow="normal" CLF.defl="clf_tree"
    //% PATH.shadow="string" PATH.defl="decision_tree_model.pkl"
    export function Savemodel(parameter: any, block: any) {
        let CLF=parameter.CLF.code;
        let PATH=parameter.PATH.code;
        Generator.addCode(`joblib.dump(${CLF}, r${PATH})`)
    }
    //% block="对象名[OBJECT]保存标签编码器到[PATH]" blockType="command"
    //% OBJECT.shadow="normal" OBJECT.defl="label_encoder"
    //% PATH.shadow="string" PATH.defl="label_encoder.pkl"
    export function Savemodel1(parameter: any, block: any) {
        let OBJECT=parameter.OBJECT.code;
        let PATH=parameter.PATH.code;
        Generator.addCode(`${OBJECT} = joblib.dump(${OBJECT}, r${PATH})`)
    } 
    //% block="---" blockType="tag"
    export function initmodel6() {}
    //% block="加载训练后[PATH]的模型或标签编码器返回结果存入变量[OBJ]中" blockType="command"
    //% PATH.shadow="string" PATH.defl="decision_tree_model.pkl"
    //% OBJ.shadow="normal" OBJ.defl="clf_tree"
    export function Loadmodel(parameter: any, block: any) {
        let OBJ=parameter.OBJ.code;
        let PATH=parameter.PATH.code;
        Generator.addCode(`${OBJ} = joblib.load(r${PATH})`)
    } 
}
